package org.summerframework.component.security.spring.access;

import org.summerframework.component.security.core.interceptor.SecurityInterceptor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * @author 石超
 * @version v1.0.0
 */
public class RoleAdminVoter implements AccessDecisionVoter<Object> {

    @Setter
    @Getter
    private String rolePrefix = "ROLE_";

    @Override
    public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
        if (authentication == null) {
            return ACCESS_DENIED;
        }
        int result = ACCESS_ABSTAIN;
        Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);

        for (ConfigAttribute attribute : attributes) {
            //判断是否是超级管理员
            if (authorities.stream().anyMatch(authority -> authority.getAuthority().equals(rolePrefix + SecurityInterceptor.ADMIN))) {
                return ACCESS_GRANTED;
            }

            if (this.supports(attribute)) {
                result = ACCESS_DENIED;

                // Attempt to find a matching granted authority
                for (GrantedAuthority authority : authorities) {
                    if (attribute.getAttribute().equals(authority.getAuthority())) {
                        return ACCESS_GRANTED;
                    }
                }
            }
        }

        return result;
    }


    public boolean supports(ConfigAttribute attribute) {
        return (attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix());
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    private Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
        return authentication.getAuthorities();
    }
}
